package com.mediacloud.app.newsmodule.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;


import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sbhandmark.pulltorefresh.library.HeaderGridView;
import com.sbhandmark.pulltorefresh.library.PullToRefreshBase;
import com.sbhandmark.pulltorefresh.library.PullToRefreshGridView;
import com.mediacloud.app.assembly.util.ConfiguRation;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.views.GlideRoundTransform;
import android.widget.TextView;
import com.mediacloud.app.model.activity.BaseBackActivity4NoDetail;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.FollowDataReceiver;
import com.mediacloud.app.model.news.FollowItem;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.GetInterestInvoker;
import com.mediacloud.app.newsmodule.utils.InterestInvoker;

import java.util.ArrayList;
import java.util.List;

public class FollowActivity extends BaseBackActivity4NoDetail {
    private PullToRefreshGridView mGridView;
    private TextView mButton;
    private FollowAdapter mAdapter;
    private GetInterestInvoker getInterestInvoker;
    private GetInterestCallBack getCallBack;
    private PullInterestCallBack pullCallBack;
    private InterestInvoker pullInterestInvoker;
    private int perPage = 8;
    private int page = 1;
    private boolean haveMore = true;

    @Override
    public int getLayoutResID() {
        return R.layout.activity_follow;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        setInvoker();
        getInterestTagList();
        setListener();
    }

    private void setInvoker() {
        getCallBack = new GetInterestCallBack();
        getInterestInvoker = new GetInterestInvoker(getCallBack);
        pullCallBack = new PullInterestCallBack();
        pullInterestInvoker = new InterestInvoker(pullCallBack);
    }

    private void getInterestTagList() {
        getInterestInvoker.getInterestTagList(page, perPage);
    }

    private void initView() {
        setTitle(R.string.interest);
        mGridView = Utility.findViewById(mRootView, R.id.follow_gridView);
        mButton = Utility.findViewById(mRootView, R.id.follow_sure);
        mAdapter = new FollowAdapter(this);
        mGridView.setAdapter(mAdapter);
        mGridView.getRefreshableView();
        mGridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
    }


    private void setListener() {
        mGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<HeaderGridView>() {
            @Override
            public void onRefresh(PullToRefreshBase<HeaderGridView> pullToRefreshBase) {
                page = 1;
                getInterestTagList();
            }
        });
        mGridView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!haveMore)
                    return;
                page++;
                getInterestTagList();
            }
        });
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FollowItem item = (FollowItem) mAdapter.getItem(position);
                mAdapter.setSelected(item);
                if (mAdapter.getSelected().size() > 0) {
                    mButton.setBackgroundColor(DefaultBgUtil.getTintColor(FollowActivity.this));
                    mButton.setText(getResources().getString(R.string.sure) + "（" + mAdapter.getSelected().size() + "）");
                } else {
                    mButton.setBackgroundColor(0xffe4e4e4);
                    mButton.setText(R.string.sure);
                }
            }
        });

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void finish() {
        UserInfo mUser = UserInfo.getUserInfo(this);
        ConfiguRation config = new ConfiguRation(this);
        config.shardBoolean("FOLLOW_" + mUser.getUserid(), true);
        if (mAdapter.getSelected().size() > 0) {
            String preference = "";
            for (FollowItem item : mAdapter.getSelected()) {
                preference += item.getTagName() + ",";
            }
            pullInterestInvoker.addInsterestTag(mUser.getUserid(), preference.substring(0, preference.length() - 1));
        }

        super.finish();
    }

    /**
     * 提交兴趣 回调接口
     */
    class PullInterestCallBack implements DataInvokeCallBack<BaseMessageReciver> {


        @Override
        public void success(BaseMessageReciver data) {

        }

        @Override
        public void fault(Object data) {

        }
    }

    /**
     * 获取兴趣列表 回调接口
     */
    class GetInterestCallBack implements DataInvokeCallBack<FollowDataReceiver> {
        @Override
        public void success(FollowDataReceiver data) {
            mGridView.onRefreshComplete();
            if (data.state) {
                if (page == 1) {
                    mAdapter.setItems(data.items);
                } else {
                    mAdapter.addItems(data.items);
                }
                haveMore = data.haveMore;
            }
        }

        @Override
        public void fault(Object data) {
            mGridView.onRefreshComplete();
        }
    }


    class FollowAdapter extends BaseAdapter {
        private Context mContext;
        private List<FollowItem> items;
        private List<FollowItem> selected;

        public FollowAdapter(Context mContext) {
            this.mContext = mContext;
            items = new ArrayList<>();
            selected = new ArrayList<>();
        }

        public void setItems(List<FollowItem> items) {
            this.items.clear();
            this.selected.clear();
            this.items.addAll(items);
            notifyDataSetChanged();
        }

        public void addItems(List<FollowItem> items) {
            this.items.addAll(items);
            notifyDataSetChanged();
        }

        public void setSelected(FollowItem item) {
            if (selected.contains(item)) {
                selected.remove(item);
            } else {
                selected.add(item);
            }
            notifyDataSetChanged();
        }

        public List<FollowItem> getSelected() {
            return selected;
        }

        @Override
        public int getCount() {
            return items.size() > 0 ? items.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mContext, R.layout.follow_item, null);
                holder.mSelectedView = convertView.findViewById(R.id.follow_item_selected);
                holder.tagImage = convertView.findViewById(R.id.follow_item_img);
                holder.tagName = convertView.findViewById(R.id.follow_item_title);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.tagImage.getLayoutParams();
            params.width = (getWindowManager().getDefaultDisplay().getWidth() - Utility.dpToPx(mContext, 30)) / 2;
            params.height = params.width;
            holder.tagImage.setLayoutParams(params);
            holder.mSelectedView.setLayoutParams(params);
            FollowItem item = items.get(position);

            RequestOptions myOptions = new RequestOptions()
                    .centerCrop()
                    .transform(new GlideRoundTransform(mContext,Utility.dpToPx(mContext, 1.6875f)));
            Glide.with(mContext)
                    .load(item.getTagImage())
                    .into(holder.tagImage);
            holder.tagName.setText(item.getTagName());
            if (selected.contains(item)) {
                holder.mSelectedView.setVisibility(View.VISIBLE);
            } else {
                holder.mSelectedView.setVisibility(View.GONE);
            }
            return convertView;
        }

        class ViewHolder {
            View mSelectedView;
            ImageView tagImage;
            TextView tagName;
        }
    }
}